package com.ruoyi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.cangku.domain.Kucunguanli;
import com.ruoyi.cangku.domain.Shangpinguanli;
import com.ruoyi.cangku.mapper.KucunguanliMapper;
import com.ruoyi.cangku.mapper.ShangpinguanliMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jinchuguanli.domain.*;
import com.ruoyi.mainDoMain.OAUser;
import com.ruoyi.mainDoMain.OAVO;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tongji.domain.GuiGeSelect;
import com.ruoyi.tongji.domain.JieCunShangPin;
import com.ruoyi.tongji.domain.ShangPinXiangQing;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class gongjulei {

    public static String authToken = "";
    public static List<OAUser> userList = new ArrayList<>();

    public static void kucunUpdate(String shangpinbianhao, KucunguanliMapper kucunguanliMapper, String type) {
        List<Shangpin> shangpinList = JSONObject.parseArray(shangpinbianhao, Shangpin.class);
        List<Kucunguanli> kucunguanlis;
        for (Shangpin s : shangpinList) {
            Kucunguanli kucunguanli = new Kucunguanli();
            kucunguanli.setShangpinbianhao(s.getShangpinbianhao());
            kucunguanlis = kucunguanliMapper.selectKucunguanliList(kucunguanli);
            if (kucunguanlis.size() > 0) {
                kucunguanli = kucunguanlis.get(0);
                if (type.equals("+")) {
                    kucunguanli.setShangpinshuliang(kucunguanli.getShangpinshuliang() + s.getShangpinshuliang());
                } else {
                    kucunguanli.setShangpinshuliang(kucunguanli.getShangpinshuliang() - s.getShangpinshuliang());
                }
                if (kucunguanli.getShangpinshuliang() < 0) {
                    throw new ServiceException("商品" + s.getShangpinming() + "数量不足！");
                }
                kucunguanliMapper.updateKucunguanli(kucunguanli);
            }
        }
    }

    public static void kucunUpdate(String shangpinbianhao, String shangpindanhaoOld, KucunguanliMapper kucunguanliMapper, String type) {
        //type表示原本的单据入库后是增加还是减少
        List<Shangpin> shangpinListNew = JSONObject.parseArray(shangpinbianhao, Shangpin.class);
        List<Shangpin> shangpinListOld = JSONObject.parseArray(shangpindanhaoOld, Shangpin.class);
        List<Kucunguanli> kucunguanliList = kucunguanliMapper.selectKucunguanliList(new Kucunguanli());

        for (Shangpin so : shangpinListOld
        ) {
            for (Kucunguanli k : kucunguanliList
            ) {
                if (k.getShangpinbianhao().equals(so.getShangpinbianhao())) {
                    if (type.equals("+")) {
                        k.setShangpinshuliang(k.getShangpinshuliang() - so.getShangpinshuliang());
                    } else {
                        k.setShangpinshuliang(k.getShangpinshuliang() + so.getShangpinshuliang());
                    }
                    kucunguanliMapper.updateKucunguanli(k);
                }
            }
        }
        for (Shangpin sn : shangpinListNew
        ) {
            for (Kucunguanli k : kucunguanliList
            ) {
                if (k.getShangpinbianhao().equals(sn.getShangpinbianhao())) {
                    if (type.equals("+")) {
                        k.setShangpinshuliang(k.getShangpinshuliang() + sn.getShangpinshuliang());
                    } else {
                        k.setShangpinshuliang(k.getShangpinshuliang() - sn.getShangpinshuliang());
                    }
                    kucunguanliMapper.updateKucunguanli(k);
                }
            }
        }


    }

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static long login(String username, String password, ISysUserService userService, RestTemplate restTemplate) {
        String[] passlist = password.split("");
        String CharSelect = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String pass = "";

        for (String s : passlist) {
            int charIndexOf = CharSelect.indexOf(s) - 11;
            if (charIndexOf < 0) {
                charIndexOf = CharSelect.length() + charIndexOf;
            }
            String uncode = String.valueOf(CharSelect.charAt(charIndexOf));
            pass += uncode;
        }
//        for (SysUser userItem : userList) {
//            String pwdMd5 = new Md5Hash(username + pass + userItem.getSalt()).toHex();
//            if (pwdMd5.equals(userItem.getPassword())) {
//                return userItem.getUserId();
//            }
//        }
        //向OA后台发起请求
        //使用盐加密字段存储OA的userID，后续直接根据这个字段确认返回字段
        String url = "https://menduoquan.com/api/Login/GetJwtToken?account={account}&password={password}";
        HashMap<String, String> map = new HashMap<>();
        map.put("account", username);
        map.put("password", pass);
        // Set headers
        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
        // Create an HttpEntity with headers and body
        HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
        OAVO responseBody = restTemplate.getForObject(url, OAVO.class, map);

        if (responseBody != null && !responseBody.getData().equals("")) {
            authToken = String.valueOf(responseBody.getData());
            //查询用户信息
            url = "https://menduoquan.com/api/User/UserDetial";
            restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
            headers = new HttpHeaders();
            //存token
            headers.set("Authorization", "Bearer " + authToken);
            requestEntity = new HttpEntity<>(new HashMap<>(), headers);
            //获取用户信息
            responseBody = restTemplate.postForObject(url, requestEntity, OAVO.class);
            System.out.println(url);
            if (responseBody != null && !responseBody.getData().equals("")) {
//            userListGet(restTemplate);
                OAUser oaUser = JSONObject.parseObject(JSON.toJSONString(responseBody.getData()), OAUser.class);
                List<SysUser> userList = userService.selectUserList(new SysUser());
                System.out.println(oaUser);
                for (SysUser su : userList
                ) {
                    if (su.getSalt().equals(String.valueOf(oaUser.getUserId()))) {
                        return su.getUserId();
                    }
                }
                SysUser sysUser = new SysUser();
                sysUser.setDeptId(201L);
                if (oaUser.getDepartmentName().contains("老板")) {
                    sysUser.setDeptId(200L);
                }
                sysUser.setUserName(oaUser.getUserName());
                sysUser.setAvatar("00");
                sysUser.setPassword(new Md5Hash(oaUser.getAccount() + pass + oaUser.getUserId()).toHex());
                sysUser.setSalt(String.valueOf(oaUser.getUserId()));
                sysUser.setPhonenumber(oaUser.getUserPhone());
                sysUser.setLoginName(oaUser.getAccount());
                userService.insertUser(sysUser);

                long uid = userService.selectUserList(sysUser).get(0).getUserId();
                userService.insertUserAuth(uid, new Long[]{2L});
                return uid;
            }
        } else {
            authToken = "";
            System.out.println(username);
            List<SysUser> userList = userService.selectUserList(new SysUser());
            for (SysUser su : userList
            ) {
                String str = new Md5Hash(username + pass + su.getSalt()).toHex();
                if (su.getPassword().equals(str) && su.getLoginName().equals(username)) {
                    return su.getUserId();
                }
            }
        }

        return -1;
    }

    private static void userListGet(RestTemplate restTemplate) {
        String url = "https://menduoquan.com/api/User/UserLsit";
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        HttpHeaders headers = new HttpHeaders();
        //存token
        headers.set("Authorization", "Bearer " + authToken);
        HttpEntity<HashMap<Object, Object>> requestEntity = new HttpEntity<>(new HashMap<>(), headers);
        //获取用户信息
        OAVO responseBody = restTemplate.getForObject(url, OAVO.class, requestEntity);
        if (responseBody != null && !responseBody.getData().equals("")) {
            userList = JSONArray.parseArray(JSON.toJSONString(responseBody.getData()), OAUser.class);
        }
    }

    public static boolean peitao(Xiaoshouchuku xiaoshouchuku, ShangpinguanliMapper shangpinguanliMapper) {
        XiaoshouchukuReturn xiaoshouchukuReturn = aReturnFormat(xiaoshouchuku, shangpinguanliMapper);
        List<Shangpin> shangpinList = xiaoshouchukuReturn.getShangpin();
        List<Shangpin> menList = new ArrayList<>();
        List<Shangpin> kuangList = new ArrayList<>();
        int count = 0;
        for (Shangpin s : shangpinList) {
            if (s.getShangpinleibie().contains("扇") || s.getShangpinleibie().equals("卷闸门")) {
                menList.add(s);
            }
            if (s.getShangpinleibie().contains("门框")) {
                kuangList.add(s);
            }
        }
        for (Shangpin sm : menList) {
            for (Shangpin sk : kuangList) {
                //判断门扇与门框的开向是否为空，如果两个都不为空，则判断是否是同一开向
                //如果两个都为空，则默认是同一开向 sm.getShangpinkaixiang()!=null && sk.getShengchanchangshang()!=null
                //如果一个为空，一个不为空，则默认是不同开向
                boolean bo;

                if (sm.getShangpinkaixiang() != null && sk.getShangpinkaixiang() != null) {
                    if (sm.getShangpinkaixiang().equals(sk.getShangpinkaixiang())) {
                        bo = true;
                    } else {
                        bo = false;
                    }
                } else {
                    bo = sm.getShangpinkaixiang() == null && sk.getShangpinkaixiang() == null;
                }
                if (sm.getShangpinguigekuan().equals(sk.getShangpinguigekuan())
                        && sm.getShangpinguigegao().equals(sk.getShangpinguigegao())
                        && bo) {
                    if (sm.getShengchanchangshang().equals(sk.getShengchanchangshang())) {
                        count++;
                    }
                }

            }
        }
        if ((kuangList.size() > 0) && (menList.size() > 0) && count == 0) {
            return true;
        }
        return false;
    }

    public static List<XiaoshouchukuReturn> returnGet(List<Xiaoshouchuku> xiaoshouchukuList, ShangpinguanliMapper shangpinguanliMapper) {
        List<XiaoshouchukuReturn> xiaoshouchukuReturnList = new ArrayList<>();
        for (Xiaoshouchuku x : xiaoshouchukuList
        ) {
            XiaoshouchukuReturn xiaoshouchukuReturn = aReturnFormat(x, shangpinguanliMapper);
            xiaoshouchukuReturnList.add(xiaoshouchukuReturn);
        }
        PageUtils.startPage();
        return xiaoshouchukuReturnList;
    }

    public static XiaoshouchukuReturn aReturnFormat(Xiaoshouchuku xiaoshouchuku, ShangpinguanliMapper shangpinguanliMapper) {
        XiaoshouchukuReturn xiaoshouchukuReturn = new XiaoshouchukuReturn();
        BeanUtils.copyProperties(xiaoshouchuku, xiaoshouchukuReturn);
        List<ShangPinCun> shangpinList = JSONObject.parseArray(xiaoshouchuku.getShangpinbianhao(), ShangPinCun.class);
        List<Shangpin> shangpinList1 = new ArrayList<>();
        for (ShangPinCun spc : shangpinList
        ) {
            Shangpinguanli shangpinguanli = shangpinguanliMapper.selectShangpinguanliByBianHao(spc.getShangpinbianhao());
            Shangpin shangpinguanli2 = new Shangpin();
            BeanUtils.copyProperties(shangpinguanli, shangpinguanli2);
            shangpinguanli2.setShangpinshuliang(spc.getShangpinshuliang());
            shangpinList1.add(shangpinguanli2);
        }
        xiaoshouchukuReturn.setShangpin(shangpinList1);
        return xiaoshouchukuReturn;
    }

    public static GouhuorukuReturn aReturnFormat(Gouhuoruku gouhuoruku, ShangpinguanliMapper shangpinguanliMapper) {
        GouhuorukuReturn gouhuorukuReturn = new GouhuorukuReturn();
        BeanUtils.copyProperties(gouhuoruku, gouhuorukuReturn);
        List<ShangPinCun> shangpinList = JSONObject.parseArray(gouhuoruku.getShangpinbianhao(), ShangPinCun.class);
        List<Shangpin> shangpinList1 = new ArrayList<>();
        for (ShangPinCun spc : shangpinList
        ) {
            Shangpinguanli shangpinguanli = shangpinguanliMapper.selectShangpinguanliByBianHao(spc.getShangpinbianhao());
            Shangpin shangpinguanli2 = new Shangpin();
            BeanUtils.copyProperties(shangpinguanli, shangpinguanli2);
            shangpinguanli2.setShangpinshuliang(spc.getShangpinshuliang());
            shangpinList1.add(shangpinguanli2);
        }
        gouhuorukuReturn.setShangpin(shangpinList1);
        return gouhuorukuReturn;
    }

    public static TuihuochuliReturn aReturnFormat(Tuihuochuli tuihuochuli, ShangpinguanliMapper shangpinguanliMapper) {
        TuihuochuliReturn gouhuorukuReturn = new TuihuochuliReturn();
        BeanUtils.copyProperties(tuihuochuli, gouhuorukuReturn);
        List<ShangPinCun> shangpinList = JSONObject.parseArray(tuihuochuli.getTuihuoshangpin(), ShangPinCun.class);
        List<Shangpin> shangpinList1 = new ArrayList<>();
        for (ShangPinCun spc : shangpinList
        ) {
            Shangpinguanli shangpinguanli = shangpinguanliMapper.selectShangpinguanliByBianHao(spc.getShangpinbianhao());
            Shangpin shangpinguanli2 = new Shangpin();
            BeanUtils.copyProperties(shangpinguanli, shangpinguanli2);
            shangpinguanli2.setShangpinshuliang(spc.getShangpinshuliang());
            shangpinList1.add(shangpinguanli2);
        }
        gouhuorukuReturn.setShangpin(shangpinList1);
        return gouhuorukuReturn;
    }

    public static int findDupicateInArray(File[] files, String path) {
        int count = 0;
        for (File file : files) {
            if (file.getName().equals(path)) {
                count++;
            }
        }
        return count;
    }

    public static Shangpin shangpinFormat(ShangPinCun shangPinCun, ShangpinguanliMapper shangpinguanliMapper) {
        Shangpinguanli shangpinguanli = shangpinguanliMapper.selectShangpinguanliByBianHao(shangPinCun.getShangpinbianhao());
        Shangpin shangpinguanli2 = new Shangpin();
        BeanUtils.copyProperties(shangpinguanli, shangpinguanli2);
        shangpinguanli2.setShangpinshuliang(shangPinCun.getShangpinshuliang());
        return shangpinguanli2;
    }

    public static List<JieCunShangPin> aFormat(List<ShangPinXiangQing> rukuShangpinList, List<JieCunShangPin> rukuList, ShangpinguanliMapper shangpinguanliMapper) {
        for (ShangPinXiangQing sx : rukuShangpinList
        ) {
            JieCunShangPin jieCunShangPin = new JieCunShangPin();
            BeanUtils.copyProperties(sx,jieCunShangPin);
            List<ShangPinCun> shangpinList = JSONArray.parseArray(sx.getShangpinbianhao(), ShangPinCun.class);
            List<Shangpin> shangpinList1 = new ArrayList<>();
            for (ShangPinCun sc : shangpinList
            ) {
                Shangpin shangpin = gongjulei.shangpinFormat(sc, shangpinguanliMapper);
                shangpinList1.add(shangpin);
            }
            jieCunShangPin.setShangpinList(shangpinList1);
            rukuList.add(jieCunShangPin);
        }
        return rukuList;
    }

    public static List<JieCunShangPin> danAddShangpin(List<JieCunShangPin> chukuList,
                                                      List<JieCunShangPin> danChukuList,
                                                      List<String> bianhaoList,
                                                      GuiGeSelect ggs) {
        for (JieCunShangPin js : chukuList
        ) {
            for (Shangpin s : js.getShangpinList()
            ) {
                if (bianhaoList.contains(s.getShangpinbianhao())) {
                    if (ggs.getShangpinguigekuan() == s.getShangpinguigekuan()
                            && ggs.getShangpinguigegao() == s.getShangpinguigegao()) {
                        if (StringUtils.isNotEmpty(ggs.getShangpinkaixiang())) {
                            if (s.getShangpinkaixiang().equals(ggs.getShangpinkaixiang())) {
                                JieCunShangPin jieCunShangPin = new JieCunShangPin();
                                jieCunShangPin.setDateIn(js.getDateIn());
                                jieCunShangPin.setDanhao(js.getDanhao());
                                jieCunShangPin.setShengchanchangshang(s.getShengchanchangshang());
                                jieCunShangPin.setShangpinbianhao(s.getShangpinleibie());
                                jieCunShangPin.setShangpinshuliang(Math.toIntExact(s.getShangpinshuliang()));
                                danChukuList.add(jieCunShangPin);
                            }
                        } else {
                            if (ggs.getShangpinguigekuan() == 0) {
                                JieCunShangPin jieCunShangPin = new JieCunShangPin();
                                jieCunShangPin.setDateIn(js.getDateIn());
                                jieCunShangPin.setDanhao(js.getDanhao());
                                jieCunShangPin.setShangpinbianhao(s.getShangpinming());
                                jieCunShangPin.setShangpinshuliang(Math.toIntExact(s.getShangpinshuliang()));
                                danChukuList.add(jieCunShangPin);
                            }
                        }
                    }
                }
            }
        }
        return danChukuList;
    }

    public static String JsonStringFy(List<Shangpin> shangpinList){
        if (shangpinList == null || shangpinList.size() == 0) {
            return "";
        }else {
            return JSONObject.toJSONString(shangpinList);
        }
    }
}
